package zhanglu.family.socket.textline.syncclient;

import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;

import zhanglu.family.socket.bean.ErrMsg;
import zhanglu.family.socket.bean.syncbean.SyncHeadBean;
import zhanglu.family.socket.bean.syncbean.SyncMsgBean;
import zhanglu.family.socket.util.JsonUtil;

public class SyncClientHandler extends IoHandlerAdapter {
    private SyncTcpClient client; // 客户端

    /**
     * 实例化
     * 
     * @param client
     *            同步消息客户端
     * @throws Exception
     */
    public SyncClientHandler(SyncTcpClient client) throws Exception {
        this.client = client;
    }

    /**
     * sessionCreated:当一个新的连接建立时，由I/O processor thread调用；
     * 
     */
    @Override
    public void sessionCreated(IoSession session) throws Exception {

    }

    /**
     * sessionOpened:当连接打开是调用
     */
    @Override
    public void sessionOpened(IoSession session) throws Exception {

    }

    /**
     * messageReceived:当接收了一个消息时调用,这个也是最重要的
     */
    @Override
    public void messageReceived(IoSession session, Object message) throws Exception {

        SyncHeadBean bean = (SyncHeadBean) JsonUtil.StringToOb(message, SyncHeadBean.class);

        SyncMsgBean resultMsg = client.synMsgMap.get(bean.getSeqId());// 获取同步对象
        if (null != resultMsg && resultMsg.getErrMsg() == ErrMsg.WAIT) {// 如果能获取同步map并且处于等待状态，说明发送的同步消息。
            resultMsg.setJsonMsg(message.toString());
            resultMsg.setErrMsg(ErrMsg.NONE);
            client.synMsgMap.put(bean.getSeqId(), resultMsg);
        }

    }

    /**
     * messageSent：当一个消息被(IoSession#write)发送出去后调用
     */
    @Override
    public void messageSent(IoSession session, Object message) throws Exception {

    }

    /**
     * sessionIdle:当连接进入空闲状态时调用,同步消息可重写后方法清空
     */
    @Override
    public void sessionIdle(IoSession session, IdleStatus status) throws Exception {
        client.dispose();
    }

    /**
     * sessionClosed:当连接关闭时调用,同步消息可重写后方法清空
     */
    @Override
    public void sessionClosed(IoSession session) throws Exception {
        client.dispose();
    }

    /**
     * exceptionCaught:当实现IoHandler的类抛出异常时调用,同步消息可重写后方法清空
     */
    @Override
    public void exceptionCaught(IoSession session, Throwable cause) throws Exception {
        client.dispose();
    }
}
